<!--
 * Copyright © 2023
 * @Author: zhangxiang
 * @Date: 2023-09-21 16:34:18
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-09-23 11:25:14
 * @Description:
 *
-->

<template>
  <MyContainer class="container">
    <MyHeader class="header">
      <span class="name">指标类型</span>
      <el-select
        v-model="indicatorType"
        placeholder="请选择指标类型"
        size="medium"
        style="width: 150px; margin-left: 10px; margin-right: 20px"
        @change="indicatorTypeChange"
      >
        <el-option
          v-for="item in indicatorTypeOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <span class="name">指标名称</span>
      <el-select
        v-model="indicatorName"
        placeholder="请选择指标名称"
        size="medium"
        style="width: 220px; margin-left: 10px; margin-right: 20px"
        filterable
        remote
        :remote-method="indicatorNameRemoteQuery"
        :loading="indicatorNameLoading"
        @change="indicatorNameChange"
      >
        <el-option
          v-for="item in indicatorNameOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button
        size="medium"
        type="primary"
        :loading="loading"
        @click="queryClick"
      >查询</el-button>
      <el-button size="medium" @click="resetClick">重置</el-button>
      <el-button
        size="medium"
        type="primary"
        :loading="exportLoading"
        style="margin-left: auto"
        @click="exportClick"
      >导出</el-button>
    </MyHeader>

    <MyMain class="main">
      <el-table
        v-loading="loading"
        class="common-table"
        :data="list"
        stripe
        header-cell-class-name="listHeaderCell"
        :header-cell-style="{ color: '#696969' }"
      >
        <el-table-column
          prop="indicatorType"
          label="指标类型"
          min-width="110"
          show-overflow-tooltip
        />
        <el-table-column
          prop="key"
          label="指标名称"
          min-width="190"
          show-overflow-tooltip
        />
        <el-table-column
          prop="unit"
          label="指标单位"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="showFlag"
          label="指标是否可见"
          min-width="110"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.showFlag ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column
          v-for="item in dynamicColumns"
          :key="item"
          :prop="item"
          :label="item"
          min-width="120"
          show-overflow-tooltip
        />
      </el-table>
    </MyMain>
  </MyContainer>
</template>

<script>
import pagePermissionMixin from '@/views/mixin/pagePermission.js'
import MyContainer from '@/components/Layout/MyContainer.vue'
import MyHeader from '@/components/Layout/MyHeader.vue'
import MyMain from '@/components/Layout/MyMain.vue'
import {
  getIndicatorList,
  getIndicatorName,
  getMesaureExport
} from '@/api/cnap/scheduling-engine'

const INDICATOR_TYPE = ['算力度量', '网络度量']

export default {
  name: 'SystemMonitorCNResPM',
  components: {
    MyContainer,
    MyHeader,
    MyMain
  },
  mixins: [pagePermissionMixin],
  data() {
    return {
      loading: false,
      indicatorType: '', // 指标类型
      indicatorName: '', // 指标名称
      indicatorTypeOptions: INDICATOR_TYPE, // 指标类型 选项
      indicatorNameOptions: [], // 指标名称 选项
      indicatorNameLoading: false,
      exportLoading: false,
      dynamicColumns: [],
      list: []
    }
  },
  created() {
    this.initData()
  },
  methods: {
    /**
     * @description: 导出
     * @return {*}
     */
    exportClick() {
      this.exportLoading = true // 展示导出loading
      // 请求
      getMesaureExport()
        .then((response) => {
          const fileNames =
            response.headers['content-disposition'].split("filename*=utf-8''") // 读取文件名
          const fileName =
            fileNames.length > 1
              ? decodeURIComponent(fileNames[1])
              : '算网度量模型.xlsx' // 解析文件名
          const blob = new Blob([response.data], {
            type: 'application/vnd.ms-excel'
          }) // 新建blob
          const elementA = document.createElement('a') // 创建 element a
          elementA.style.display = 'none' // 设置不可见
          elementA.href = window.URL.createObjectURL(blob) // 设置href
          elementA.download = fileName // 设置名称
          document.body.appendChild(elementA) // 添加到body
          elementA.click() // 模拟点击
          window.URL.revokeObjectURL(elementA.href) // 释放内存
        })
        .catch((err) => {
          console.log(err)
          this.$message.error('导出失败，请稍候再试') // 导出失败
        })
        .finally(() => {
          this.exportLoading = false // 取消loading
        })
    },
    /**
     * @description: 指标名称查询
     * @param {*} query
     * @return {*}
     */
    indicatorNameRemoteQuery(query) {
      this.indicatorNameLoading = true
      getIndicatorName({
        indicatorType: this.indicatorType,
        key: query
      })
        .then((res) => {
          if (Array.isArray(res.data)) {
            this.indicatorNameOptions = res.data.map((item) => {
              return {
                label: item,
                value: item
              }
            })
          }
        })
        .finally(() => {
          this.indicatorNameLoading = false
        })
    },
    /**
     * @description: 指标名称 变化
     * @param {*} val
     * @return {*}
     */
    indicatorNameChange(val) {},
    /**
     * @description: 指标类型 变化
     * @param {*} val
     * @return {*}
     */
    indicatorTypeChange(val) {
      this.indicatorName = ''
      this.indicatorNameOptions = []
      this.indicatorNameRemoteQuery('')
    },
    /**
     * @description: 重置搜索框
     * @return {*}
     */
    resetClick() {
      this.indicatorType = ''
      this.indicatorName = ''
      this.indicatorNameOptions = []
      this.indicatorNameRemoteQuery('')
      this.getIndicatorData()
    },
    /**
     * @description: 搜索
     * @return {*}
     */
    queryClick() {
      this.getIndicatorData()
    },
    /**
     * @description:
     * @param {*} respList
     * @return {*}
     */
    handleRespList(respList) {
      const dynamicColumns = [] // 动态获取的指标
      respList.forEach((element) => {
        if (!dynamicColumns.includes(element.type)) {
          dynamicColumns.push(element.type)
        }
      })
      const list = []
      respList.forEach((element) => {
        const findIndex = list.findIndex((item) => {
          // 指标类型 + 指标名称 唯一一行
          return (
            item.indicatorType === element.indicatorType &&
            item.key === element.key
          )
        })
        if (findIndex >= 0) {
          // 有 则新增指标字段
          if (
            !Object.prototype.hasOwnProperty.call(list[findIndex], element.type)
          ) {
            list[findIndex][element.type] = element.value
          }
        } else {
          // 没有则新增一行
          const column = {
            ...element
          }
          column[element.type] = element.value
          list.push(column)
        }
      })
      list.sort((x, y) => {
        return (
          INDICATOR_TYPE.indexOf(x.indicatorType) -
          INDICATOR_TYPE.indexOf(y.indicatorType)
        )
      })
      this.dynamicColumns = dynamicColumns
      this.list = list
    },
    /**
     * @description: 获取指标数据
     * @return {*}
     */
    getIndicatorData() {
      this.loading = true
      getIndicatorList({
        indicatorType: this.indicatorType,
        indicatorName: this.indicatorName,
        pageNum: 1,
        pageSize: 1000
      })
        .then((res) => {
          const list =
            res.data && Array.isArray(res.data.data) ? res.data.data : []
          this.handleRespList(list)
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * @description: 初始化数据
     * @return {*}
     */
    initData() {
      this.queryClick()
      this.indicatorNameRemoteQuery('')
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.container {
}
</style>
